package cn.com.cetccst.basiccollection.peroid;

import android.content.Context;
import android.util.Log;

import androidx.work.Data;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import java.util.concurrent.TimeUnit;

import cn.com.cetccst.basiccollection.InfoType;
import cn.com.cetccst.datacenter.collection.entity.CollectionConfigEntity;

public class PeroidCollectHelper {
    public static final String TAG = "PeroidCollectHelper";
    private Context mContext;

    public PeroidCollectHelper(Context context) {
        mContext = context;

    }

    public void startWorker(CollectionConfigEntity config) {
        if (config == null) {
            Log.e(TAG, "no data connection config, skip start worker");
            return;
        }

        //根据具体协议修改
        start(config.isEnabled(), InfoType.HARDWARE_INFO, config.getHardware());
        start(config.isEnabled(), InfoType.SOURCE_INFO, config.getHardware());
    }

    private void start(boolean enable, InfoType type, int interval) {
        String workerId = "ss_data_collector_" + type;
        if (!enable) {
            WorkManager.getInstance(mContext).cancelUniqueWork(workerId);
            return;
        }

        PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(CollectWorker.class,
                interval, TimeUnit.MINUTES)// 最小15分钟
                .setInitialDelay(10, TimeUnit.SECONDS)
                .setInputData(new Data.Builder().putString("type", type.name()).build())
                .build();
        WorkManager.getInstance(mContext).enqueueUniquePeriodicWork(workerId, ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE, periodicWork);
    }
}
